package com.aifeng.hassan_food.mine

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.aifeng.base.*
import com.aifeng.common_ui.base.find
import com.aifeng.common_ui.base.getColorEx
import com.aifeng.common_ui.base.gone
import com.aifeng.common_ui.base.visible
import com.aifeng.common_ui.helper.*
import com.aifeng.common_ui.view.FullyLinearLayoutManager
import com.aifeng.hassan_food.R
import com.aifeng.hassan_food.sale.ConfirmPayActivity
import com.aifeng.model.BaseUrl
import com.aifeng.model.CommonData
import com.aifeng.model.OrderData
import com.aifeng.oss.scaleImage
import com.aifeng.utils.DialogHelper.showHintDialog
import com.aifeng.utils.bindLifeCycle
import com.aifeng.utils.getExtra
import com.aifeng.utils.onTabSelectedListener
import com.aifeng.utils.subscribeByNoError
import com.aifeng.viewmodel.OrderViewModel
import com.jeremyliao.liveeventbus.utils.observe
import kotlinx.android.synthetic.main.activity_order.*
import kotlinx.android.synthetic.main.layout_empty.*
import kotlinx.android.synthetic.main.layout_list.*
import net.idik.lib.slimadapter.SlimAdapter
import org.jetbrains.anko.backgroundResource
import org.jetbrains.anko.imageResource
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.textColor
import org.koin.androidx.viewmodel.ext.android.getViewModel

class OrderActivity : BaseActivity() {

    private lateinit var mDefaultIndex: String
    private var mState = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_order)
        initTitle(title = "我的订单", divider = false)
    }

    override fun getViewModel() = getViewModel<OrderViewModel>()

    override fun initTitle(title: String, name: String, divider: Boolean) {
        super.initTitle(title, name, divider)
        mDefaultIndex = intent.getExtra("index")
        initTabLayout()
        initList()

        observe("orderList") {
            val items = it.split(",")
            when (items[0]) {
                "pay", "confirm", "cancel" -> {
                    if (mState.isNotEmpty()) {
                        mList.removeAt(items[1].toNotInt())
                        mAdapter.notifyItemRemoved(items[1].toNotInt())
                        empty_view.apply { if (mList.isEmpty()) visible() else gone() }
                    } else {
                        (mList[items[1].toNotInt()] as OrderData).state =
                            when (items[0]) {
                                "pay" -> "1"
                                "confirm" -> "99"
                                "cancel" -> "7"
                                else -> ""
                            }
                        mAdapter.notifyItemChanged(items[1].toNotInt())
                    }
                }
                "delete" -> {
                    mList.removeAt(items[1].toNotInt())
                    mAdapter.notifyItemRemoved(items[1].toNotInt())
                    empty_view.apply { if (mList.isEmpty()) visible() else gone() }
                }
            }
        }
    }

    private fun initTabLayout() {
        order_tab.apply {
            onTabSelectedListener {
                onTabSelected {
                    mState = when (it!!.position) {
                        1 -> "0"
                        2 -> "1"
                        3 -> "2"
                        4 -> "99"
                        else -> ""
                    }

                    getViewModel().cancelRequest()
                    getViewModel().delay { updateList() }
                }
            }
            addTab(
                newTab().apply {
                    setCustomView(R.layout.item_share_tab)
                    customView?.find<TextView>(R.id.item_tab_num)?.gone()
                    customView?.find<TextView>(R.id.item_tab_title)?.text = "全部"
                },
                mDefaultIndex == "1"
            )
            addTab(
                newTab().apply {
                    setCustomView(R.layout.item_share_tab)
                    customView?.find<TextView>(R.id.item_tab_num)?.gone()
                    customView?.find<TextView>(R.id.item_tab_title)?.text = "待付款"
                },
                mDefaultIndex == "2"
            )
            addTab(
                newTab().apply {
                    setCustomView(R.layout.item_share_tab)
                    customView?.find<TextView>(R.id.item_tab_num)?.gone()
                    customView?.find<TextView>(R.id.item_tab_title)?.text = "待发货"
                },
                mDefaultIndex == "3"
            )
            addTab(
                newTab().apply {
                    setCustomView(R.layout.item_share_tab)
                    customView?.find<TextView>(R.id.item_tab_num)?.gone()
                    customView?.find<TextView>(R.id.item_tab_title)?.text = "待收货"
                },
                mDefaultIndex == "4"
            )
            addTab(
                newTab().apply {
                    setCustomView(R.layout.item_share_tab)
                    customView?.find<TextView>(R.id.item_tab_num)?.gone()
                    customView?.find<TextView>(R.id.item_tab_title)?.text = "已完成"
                },
                mDefaultIndex == "5"
            )
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun initList() {
        empty_img.imageResource = R.mipmap.icon_order_no
        empty_hint.text = "暂无相关订单信息！"
        swipe_refresh.refresh { getData(1) }
        recycle_list.apply {
            (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false //去除闪烁
            loadLinear(baseContext, swipe_refresh) {
                if (!isLoadingMore) {
                    isLoadingMore = true
                    getData(pageNum)
                }
            }
        }

        mAdapter = SlimAdapter.create()
            .register<OrderData>(R.layout.item_order_list) { data, injector ->

                val index = mList.indexOf(data)
                val isLast = index == mList.size - 1

                injector.text(R.id.item_order_name, data.shopname)
                    .text(
                        R.id.item_order_price,
                        "¥ ${data.saletotal.formatDecimal()}"
                    )
                    .text(
                        R.id.item_order_total,
                        "共${data.list.size}件商品 合计: ¥ ${(data.paytotal.toNotDouble() + data.expressfee.toNotDouble()).formatDecimal()}"
                    )
                    .text(
                        R.id.item_order_status,
                        when (data.state) {
                            "0" -> "待付款"
                            "1" -> "待发货"
                            "2" -> "待收货"
                            "5" -> "退款成功"
                            "7" -> "已取消"
                            "99" -> "已完成"
                            else -> ""
                        }
                    )
                    .visibility(
                        R.id.item_order_divider,
                        if (isLast) View.VISIBLE else View.GONE
                    )
                    .with<TextView>(R.id.item_order_bt01) {
                        it.text = when (data.state) {
                            "0" -> "取消订单"
                            "2" -> "查看物流"
                            "5", "7", "99" -> "删除订单"
                            else -> ""
                        }

                        it.visibility = when (data.state) {
                            "0", "2", "5", "7", "99" -> View.VISIBLE
                            else -> View.GONE
                        }
                    }
                    .with<TextView>(R.id.item_order_bt02) {
                        if (data.state == "99") {
                            it.backgroundResource = R.drawable.rec_bg_ova_white_stroke_a3a3a3
                            it.textColor = Color.parseColor("#505050")
                        } else {
                            it.backgroundResource = R.drawable.rec_bg_ova_white_stroke_red
                            it.textColor = getColorEx(R.color.colorAccent)
                        }

                        it.text = when (data.state) {
                            "0" -> "去支付"
                            "2" -> "确认收货"
                            "99" -> "查看物流"
                            else -> ""
                        }

                        it.visibility = when (data.state) {
                            "0", "2", "99" -> View.VISIBLE
                            else -> View.GONE
                        }
                    }
                    .clicked(R.id.item_order_bt01) {
                        when (data.state) {
                            "0" -> cancelOrder(data.id, index)
                            "2" -> {
                                if (data.expressno.isNotEmpty())
                                    startActivity<OrderExpressActivity>("num" to data.expressno)
                            }
                            "5", "7", "99" -> deleteOrder(data.id, index)
                        }
                    }
                    .clicked(R.id.item_order_bt02) {
                        when (data.state) {
                            "0" -> {
                                startActivity<ConfirmPayActivity>(
                                    "orderNo" to data.orderno,
                                    "price" to data.paytotal,
                                    "express" to data.expressfee,
                                    "orderId" to data.id,
                                    "orderIndex" to index.toString()
                                )
                            }
                            "2" -> confirmOrder(data.id, index)
                            "99" -> startActivity<OrderExpressActivity>("num" to data.expressno)
                        }
                    }
                    .clicked(R.id.item_order) {
                        if (data.state == "5") {
                            startActivity<OrderRefundDetailActivity>(
                                "id" to data.id,
                                "index" to index.toString()
                            )
                        } else {
                            startActivity<OrderDetailActivity>(
                                "id" to data.id,
                                "index" to index.toString()
                            )
                        }
                    }

                    .with<RecyclerView>(R.id.item_order_list) {
                        it.apply {
                            // 拦截item中RecyclerView的点击事件
                            setOnTouchListener { _, event ->
                                return@setOnTouchListener injector.findViewById<View>(R.id.item_order)
                                    .onTouchEvent(event)
                            }

                            isNestedScrollingEnabled = false
                            layoutManager = FullyLinearLayoutManager(baseContext)
                            adapter = SlimAdapter.create()
                                .register<CommonData>(R.layout.item_shop_inner_list_80) { inner, jector ->
                                    jector.text(R.id.item_shop_name, inner.goodsname)
                                        .text(R.id.item_shop_type, "规格：${inner.specs}")
                                        .text(
                                            R.id.item_shop_price,
                                            setHtmlSmall("¥ ${inner.price.formatDecimalWhenHave()}", "¥")
                                        )
                                        .text(R.id.item_shop_num, "x${inner.num}")
                                        .with<ImageView>(R.id.item_shop_img) { view ->
                                            val imgs = inner.goodimg.split(",")
                                            view.loadRoundedImage(url = imgs[0].scaleImage())
                                        }
                                        .visibility(
                                            R.id.item_shop_set,
                                            if (inner.specstype == "package") View.VISIBLE else View.GONE
                                        )
                                }
                        }

                        (it.adapter as SlimAdapter).updateData(data.list)
                    }
            }
            .attachTo(recycle_list)
    }

    private fun confirmOrder(orderId: String, index: Int) {
        showHintDialog(
            title = "确认收货",
            hint = "确认已收到购买的商品？"
        ) {
            getViewModel().orderHandle(
                url = BaseUrl.confirmGoods,
                orderId = orderId,
                userId = getString("userId")
            )
                .bindLifeCycle(getLifecycleOwner())
                .subscribeByNoError(
                    event = getViewModel(),
                    onSuccess = {
                        if (mState.isNotEmpty()) {
                            mList.removeAt(index)
                            mAdapter.notifyItemRemoved(index)
                            empty_view.apply { if (mList.isEmpty()) visible() else gone() }
                        } else {
                            (mList[index] as OrderData).state = "99"
                            mAdapter.notifyItemChanged(index)
                        }
                    }
                )
        }
    }

    private fun cancelOrder(orderId: String, index: Int) {
        showHintDialog(
            title = "取消订单",
            hint = "确定要取消订单吗？"
        ) {
            getViewModel().orderHandle(
                url = BaseUrl.cancelOrder,
                orderId = orderId,
                userId = getString("userId")
            )
                .bindLifeCycle(getLifecycleOwner())
                .subscribeByNoError(
                    event = getViewModel(),
                    onSuccess = {
                        if (mState.isNotEmpty()) {
                            mList.removeAt(index)
                            mAdapter.notifyItemRemoved(index)
                            empty_view.apply { if (mList.isEmpty()) visible() else gone() }
                        } else {
                            (mList[index] as OrderData).state = "7"
                            mAdapter.notifyItemChanged(index)
                        }
                    }
                )
        }
    }

    private fun deleteOrder(orderId: String, index: Int) {
        showHintDialog(
            title = "删除订单",
            hint = "确定要删除订单吗？"
        ) {
            getViewModel().orderHandle(
                url = BaseUrl.delOrder,
                orderId = orderId,
                userId = getString("userId")
            )
                .bindLifeCycle(getLifecycleOwner())
                .subscribeByNoError(
                    event = getViewModel(),
                    onSuccess = {
                        mList.removeAt(index)
                        mAdapter.notifyItemRemoved(index)
                        empty_view.apply { if (mList.isEmpty()) visible() else gone() }
                    }
                )
        }
    }

    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel().orderList(
            page = index,
            state = mState,
            userId = getString("userId"),
            onSuccess = {
                mList.apply {
                    if (index == 1) {
                        clear()
                        pageNum = index
                    }
                    addItems(it)
                    if (count(it) > 0) pageNum++
                }

                mAdapter.updateData(mList)
            },
            onFinally = {
                swipe_refresh.isRefreshing = false
                isLoadingMore = false
                empty_view.apply { if (mList.isEmpty()) visible() else gone() }
            }
        )
    }

    private fun updateList() {
        swipe_refresh.isRefreshing = true

        empty_view.gone()
        if (mList.isNotEmpty()) {
            mList.clear()
            mAdapter.notifyDataSetChanged()
        }

        pageNum = 1
        getData(pageNum)
    }

}
